#!/bin/bash
# Ambari Cluster Stop Script
# Usage: ./ambari-stop-cluster.sh

set -e

# 配置参数
AMBARI_SERVER="hadoop-app"
SSH_USER="root"
SSH_OPTS="-o StrictHostKeyChecking=no -o ConnectTimeout=5"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"
}

# 停止Ambari Agents
stop_ambari_agents() {
    local hosts=("hadoop-node1" "hadoop-node2" "hadoop-node3")
    
    for host in "${hosts[@]}"; do
        log_info "正在停止Ambari Agent ($host)..."
        if ssh $SSH_OPTS $SSH_USER@$host "ambari-agent stop" &>/dev/null; then
            log_info "Ambari Agent $host 停止成功"
        else
            log_warn "Ambari Agent $host 停止失败（可能未运行）"
        fi
    done
}

# 停止Ambari Server
stop_ambari_server() {
    log_info "正在停止Ambari Server ($AMBARI_SERVER)..."
    if ssh $SSH_OPTS $SSH_USER@$AMBARI_SERVER "ambari-server stop" &>/dev/null; then
        log_info "Ambari Server 停止成功"
    else
        log_warn "Ambari Server 停止失败（可能未运行）"
    fi
}

# 强制杀死进程（如果正常停止失败）
force_kill_processes() {
    local hosts=("hadoop-app" "hadoop-node1" "hadoop-node2" "hadoop-node3")
    
    for host in "${hosts[@]}"; do
        log_info "检查并清理 $host 上的残留进程..."
        ssh $SSH_OPTS $SSH_USER@$host "pkill -f ambari-agent || true"
        ssh $SSH_OPTS $SSH_USER@$host "pkill -f ambari-server || true"
    done
}

# 检查服务状态
check_services_status() {
    log_info "检查服务停止状态..."
    
    local hosts=("hadoop-app" "hadoop-node1" "hadoop-node2" "hadoop-node3")
    for host in "${hosts[@]}"; do
        echo "=== $host ==="
        ssh $SSH_OPTS $SSH_USER@$host "ps -ef | grep -E '(ambari-agent|ambari-server)' | grep -v grep" || true
    done
}

# 主函数
main() {
    log_info "开始停止Ambari集群..."
    
    # 停止所有Ambari Agents
    stop_ambari_agents
    
    # 停止Ambari Server
    stop_ambari_server
    
    # 等待进程停止
    sleep 5
    
    # 强制清理残留进程
    force_kill_processes
    
    # 检查最终状态
    check_services_status
    
    log_info "Ambari集群已完全停止!"
}

main "$@"
